/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package port4j;

import java.io.*;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Set;

/**
 *
 * @author Bryce
 */
public class Port4J {

    private static final String DEFAULT_FILENAME = "config.txt";
    private static final String DEFAULT_LOGNAME = "forwarderLog.txt";
    private String configFileName;

    public Port4J() throws FileNotFoundException, IOException {
        //No arg constructor
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        //open the file
        FileInputStream fstream = new FileInputStream(DEFAULT_FILENAME);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //read file line by line
        //Format: <sourceIP>:<sourcePort> <destIp>:<destPort>
        //For each entry, create a forwarder instance
        ArrayList<String> sources = new ArrayList<String>();
        ArrayList<String> destinations = new ArrayList<String>();
        while ((strLine = br.readLine()) != null) {
            String[] configs = strLine.split(" ");
            sources.add(configs[0]);
            destinations.add(configs[1]);
        }
        String[] allClients = new String[sources.size()];
        String[] allDestinations = new String[destinations.size()];
        destinations.toArray(allDestinations);
        sources.toArray(allClients);
        Set uniquePorts = Mapper.getListenerList(allClients);
        String[] ports = new String[uniquePorts.size()];
        uniquePorts.toArray(ports);
        for(String port : ports) {
            //Create a new Forwarder implementation & run it
            Mapper mapper = new Mapper(allClients, allDestinations);
            DataWorker worker = new DataWorker();
            new Thread(worker).start();
            //InetAddress srcAddr = InetAddress.getByName(source[0]);
            new Thread(new Forwarder(null, Integer.parseInt(port), worker, mapper, DEFAULT_LOGNAME)).start();
        }
    }
}
